package com.fjw.service.impl;

import com.fjw.mapper.OrderMapper;
import com.fjw.mapper.TeaMapper;
import com.fjw.pojo.Order;
import com.fjw.pojo.Tea;
import com.fjw.service.OrderService;
import com.fjw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private TeaMapper teaMapper;

    @Override
    @Transactional
    public void createOrder(Order order) {
        // 验证用户存在（调用现有UserService方法）
        userService.findById(order.getUserId());

        // 验证并处理 tea_ids
        validateAndProcessTeaIds(order);

        // 计算总价
        calculateTotalPrice(order);

        // 保存订单
        orderMapper.insert(order);
    }

    private void validateAndProcessTeaIds(Order order) {
        String teaIds = order.getTeaIds();
        if (teaIds == null || teaIds.isEmpty()) {
            throw new IllegalArgumentException("tea_ids不能为空");
        }

        // 验证每个 tea_id 是否存在（调用现有TeaMapper方法）
        List<Integer> teaIdList = Arrays.stream(teaIds.split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        List<Tea> validTeas = teaMapper.findByIds(teaIdList);
        if (validTeas.size() != teaIdList.size()) {
            // 找出不存在的 tea_id
            Set<Integer> validIds = validTeas.stream().map(Tea::getId).collect(Collectors.toSet());
            List<Integer> invalidIds = teaIdList.stream()
                    .filter(id -> !validIds.contains(id))
                    .collect(Collectors.toList());
            throw new IllegalArgumentException("无效的饮品ID: " + invalidIds);
        }
    }

    private void calculateTotalPrice(Order order) {
        List<Integer> teaIdList = Arrays.stream(order.getTeaIds().split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        List<Tea> teas = teaMapper.findByIds(teaIdList);
        BigDecimal totalPrice = teas.stream()
                .map(tea -> new BigDecimal(tea.getRmb())) // 手动转换 String -> BigDecimal
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        order.setTotalPrice(totalPrice);
    }

    @Override
    public Order findById(Integer id) {
        Order order = orderMapper.findById(id);
        if (order != null) {
            associateUserAndTeas(order);
        }
        return order;
    }

    @Override
    public List<Order> findByUserId(Integer userId) {
        List<Order> orders = orderMapper.findByUserId(userId);
        orders.forEach(this::associateUserAndTeas);
        return orders;
    }

    @Override
    public List<Order> findAll() {
        List<Order> orders = orderMapper.findAll();
        orders.forEach(this::associateUserAndTeas);
        return orders;
    }

    private void associateUserAndTeas(Order order) {
        // 关联用户信息（调用现有UserService方法）
        order.setUser(userService.findById(order.getUserId()));

        // 关联饮品信息（调用现有TeaMapper方法）
        if (order.getTeaIds() != null && !order.getTeaIds().isEmpty()) {
            List<Integer> teaIdList = Arrays.stream(order.getTeaIds().split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            List<Tea> teas = teaMapper.findByIds(teaIdList);
            order.setTeas(teas);
        }
    }

    @Override
    @Transactional
    public void updateStatus(Integer id, Integer status) {
        orderMapper.updateStatus(id, status);
    }

    @Override
    @Transactional
    public void deleteById(Integer id) {
        orderMapper.deleteById(id);
    }
}